import React from 'react';
import { Modal, Button, Upload } from 'antd';
import { CloudUploadOutlined, PlusOutlined } from '@ant-design/icons';
import { uploadImg } from '@/services/admin/common/api';
interface TypeProps {
  onChange: any;
  previewVisible?: boolean;
  previewImage?: any;
  previewTitle?: string;
  fileList?: [];
}
class CUploadImage extends React.Component<any, TypeProps> {
  constructor(props: TypeProps) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList: [],
      ...props,
    };
  }
  render() {
    return (
      <>
        <Button
          type="primary"
          onClick={() => {
            this.setState({
              previewVisible: true,
            });
          }}
        >
          <CloudUploadOutlined />
          上传图片
        </Button>
        <Modal
          title="图片上传"
          visible={this.state.previewVisible}
          footer={null}
          destroyOnClose
          onCancel={() => {
            this.setState({
              previewVisible: false,
              fileList: [],
            });
            this.state.onChange();
          }}
        >
          <Upload
            listType="picture-card"
            multiple={true}
            fileList={this.state.fileList}
            // beforeUpload={(file) => {
            //   // 控制上传图片格式
            //   const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            //   if (!isJpgOrPng) {
            //     message.error('您只能上传JPG/PNG 文件!');
            //     return;
            //   }
            //   const isLt2M = file.size / 1024 / 1024 < 2;
            //   if (!isLt2M) {
            //     message.error('图片大小必须小于2MB!');
            //     return;
            //   }
            // }}
            customRequest={async (info: any) => {
              const { file, onError, onSuccess } = info;
              const formData = new FormData();
              formData.append('file', file);
              const res = await uploadImg(formData);
              if (res.status === 20000) {
                onSuccess();
                const fileList: any = this.state.fileList;
                fileList?.push({
                  uid: res.data.image_id,
                  name: res.data.url,
                  url: res.data.url,
                });
                this.setState({ fileList: fileList });
              } else {
                onError();
              }
            }}
          >
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传图片</div>
            </div>
          </Upload>
        </Modal>
      </>
    );
  }
}
export default CUploadImage;
